package org.jctc.els.modules.biz.service.pro.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.codehaus.janino.IClass;
import org.jctc.els.common.constant.BaseRoleConstant;
import org.jctc.els.modules.biz.entity.pro.*;
import org.jctc.els.modules.biz.entity.proTemplate.ProjectReviewTemplate;
import org.jctc.els.modules.biz.entity.projects.ElsProjects;
import org.jctc.els.modules.biz.entity.user.User;
import org.jctc.els.modules.biz.mapper.pro.ElsProjectReviewMapper;
import org.jctc.els.modules.biz.mapper.pro.ProjectReviewDetailedMapper;
import org.jctc.els.modules.biz.mapper.pro.ProjectReviewOptionsMapper;
import org.jctc.els.modules.biz.mapper.proTemplate.ProjectReviewTemplateMapper;
import org.jctc.els.modules.biz.mapper.projects.ElsProjectsMapper;
import org.jctc.els.modules.biz.mapper.user.UserMapper;
import org.jctc.els.modules.biz.service.pro.ElsProjectReviewService;
import org.jctc.els.modules.biz.vo.ElsProjectTeamAuditVO;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.BaseRoleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评审表;(els_project_review)表服务实现类
 *
 * @author : http://www.chiner.pro
 * @date : 2022-6-21
 */
@Service
public class ElsProjectReviewServiceImpl implements ElsProjectReviewService {
    @Autowired
    private ElsProjectReviewMapper elsProjectReviewMapper;
    @Autowired
    private ProjectReviewDetailedMapper projectReviewDetailedMapper;
    @Autowired
    private ProjectReviewOptionsMapper projectReviewOptionsMapper;
    @Autowired
    private ElsProjectsMapper elsProjectsMapper;
    @Autowired
    private ProjectReviewTemplateMapper projectReviewTemplateMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public ProjectReviewVO selectByProjectIdAndExpertId(Long projectId, Long userId) {
        ProjectReviewVO vo = new ProjectReviewVO();
        //获取模板基本信息
        ElsProjectReview projectReviewTemplate = elsProjectReviewMapper.selectOne(new QueryWrapper<ElsProjectReview>().eq("project_id", projectId).eq("user_id", userId));
        vo.setBasic(projectReviewTemplate);
        //获取一级维度
        List<ProjectReviewDetailedVO> oneLevelList = projectReviewDetailedMapper.selectLowerLevelList(projectId, 0L, 1,userId);
        //获取下级维度
        for (ProjectReviewDetailedVO oneLevel : oneLevelList) {
            List<ProjectReviewDetailedVO> twoLevelList = projectReviewDetailedMapper.selectLowerLevelList(projectId, oneLevel.getId(), 2,userId);
            //判断是否有下级维度
            if (twoLevelList.size() == 0) {
                String[] split = oneLevel.getAnswer().split(",");

                //没有下级维度 查询选项
                String[] optionIdList = oneLevel.getOptionIds().split(",");
                List<ProjectReviewOptions> optionsList = projectReviewOptionsMapper.selectList(new QueryWrapper<ProjectReviewOptions>().in("id", optionIdList));
                oneLevel.setOptionList(optionsList);
                oneLevel.setLowerLevelNum(0);
                continue;
            }
            //拥有下级维度继续查询
            oneLevel.setLowerLevel(twoLevelList);
            oneLevel.setLowerLevelNum(twoLevelList.size());
            //二级维度获取三级维度
            for (ProjectReviewDetailedVO twoLevel : twoLevelList) {
                List<ProjectReviewDetailedVO> threeLevel = projectReviewDetailedMapper.selectLowerLevelList(projectId, twoLevel.getId(), 3,userId);
                //判断是否有下级维度
                if (threeLevel.size() == 0) {
                    //没有下级维度 查询选项
                    String[] optionIdList = twoLevel.getOptionIds().split(",");
                    List<ProjectReviewOptions> optionsList = projectReviewOptionsMapper.selectList(new QueryWrapper<ProjectReviewOptions>().in("id", optionIdList));
                    twoLevel.setOptionList(optionsList);
                    twoLevel.setLowerLevelNum(0);
                    continue;
                }
                twoLevel.setLowerLevelNum(threeLevel.size());
                twoLevel.setLowerLevel(threeLevel);
                //查询三级维度下面的选项
                for (ProjectReviewDetailedVO three : threeLevel) {
                    //没有下级维度 查询选项
                    String[] optionIdList = three.getOptionIds().split(",");
                    List<ProjectReviewOptions> optionsList = projectReviewOptionsMapper.selectList(new QueryWrapper<ProjectReviewOptions>().in("id", optionIdList));
                    three.setOptionList(optionsList);
                    three.setLowerLevelNum(0);
                    continue;
                }
            }
        }
        vo.setOneLevel(oneLevelList);
        return vo;
    }


    @Override
    public IPage<ProjectReviewAuditVO> selectExpertScore(Integer pageNum, Integer pageSize, Long projectId) {
        Page<ProjectReviewAuditVO> elsProjectsPage = new Page<>(pageNum, pageSize);
        IPage<ProjectReviewAuditVO> list = elsProjectReviewMapper.selectExpertScore(elsProjectsPage, projectId);
        List<ProjectReviewAuditVO> records = list.getRecords();
        for (ProjectReviewAuditVO record : records) {
            User user = userMapper.selectById(record.getExpertId());
            record.setExpertName(user.getUserName());
        }
        list.setRecords(records);
        return list;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public ElsProjectReview queryById(Long id) {
        return elsProjectReviewMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param elsProjectReview 筛选条件
     * @param current          当前页码
     * @param size             每页大小
     * @return
     */
    public Page<ElsProjectReview> paginQuery(ElsProjectReview elsProjectReview, long current, long size) {
        //1. 构建动态查询条件
        LambdaQueryWrapper<ElsProjectReview> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(elsProjectReview.getName())) {
            queryWrapper.eq(ElsProjectReview::getName, elsProjectReview.getName());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getReviewResult())) {
            queryWrapper.eq(ElsProjectReview::getReviewResult, elsProjectReview.getReviewResult());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getRemark())) {
            queryWrapper.eq(ElsProjectReview::getRemark, elsProjectReview.getRemark());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getAdminAuthResultRemark())) {
            queryWrapper.eq(ElsProjectReview::getAdminAuthResultRemark, elsProjectReview.getAdminAuthResultRemark());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getLeaderAuthResultRemark())) {
            queryWrapper.eq(ElsProjectReview::getLeaderAuthResultRemark, elsProjectReview.getLeaderAuthResultRemark());
        }
        //2. 执行分页查询
        Page<ElsProjectReview> pagin = new Page<>(current, size, true);
        IPage<ElsProjectReview> selectResult = elsProjectReviewMapper.selectByPage(pagin, queryWrapper);
        pagin.setPages(selectResult.getPages());
        pagin.setTotal(selectResult.getTotal());
        pagin.setRecords(selectResult.getRecords());
        //3. 返回结果
        return pagin;
    }

    /**
     * 新增数据
     *
     * @param elsProjectReview 实例对象
     * @return 实例对象
     */
    public ElsProjectReview insert(ElsProjectReview elsProjectReview) {
        elsProjectReview.setCreatedTime(new Date());
        elsProjectReview.setUpdatedTime(new Date());
        elsProjectReview.setCreatedBy(AuthUtil.getUserId());
        elsProjectReview.setUpdatedBy(AuthUtil.getUserId());
        elsProjectReviewMapper.insert(elsProjectReview);
        return elsProjectReview;
    }

    /**
     * 更新数据
     *
     * @param elsProjectReview 实例对象
     * @return 实例对象
     */
    public ElsProjectReview update(ElsProjectReview elsProjectReview) {
        elsProjectReview.setUpdatedTime(new Date());
        elsProjectReview.setUpdatedBy(AuthUtil.getUserId());
        //1. 根据条件动态更新
        LambdaUpdateChainWrapper<ElsProjectReview> chainWrapper = new LambdaUpdateChainWrapper<ElsProjectReview>(elsProjectReviewMapper);
        if (StrUtil.isNotBlank(elsProjectReview.getName())) {
            chainWrapper.eq(ElsProjectReview::getName, elsProjectReview.getName());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getReviewResult())) {
            chainWrapper.eq(ElsProjectReview::getReviewResult, elsProjectReview.getReviewResult());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getRemark())) {
            chainWrapper.eq(ElsProjectReview::getRemark, elsProjectReview.getRemark());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getAdminAuthResultRemark())) {
            chainWrapper.eq(ElsProjectReview::getAdminAuthResultRemark, elsProjectReview.getAdminAuthResultRemark());
        }
        if (StrUtil.isNotBlank(elsProjectReview.getLeaderAuthResultRemark())) {
            chainWrapper.eq(ElsProjectReview::getLeaderAuthResultRemark, elsProjectReview.getLeaderAuthResultRemark());
        }
        //2. 设置主键，并更新
        chainWrapper.set(ElsProjectReview::getId, elsProjectReview.getId());
        boolean ret = chainWrapper.update();
        //3. 更新成功了，查询最最对象返回
        if (ret) {
            return queryById(elsProjectReview.getId());
        } else {
            return elsProjectReview;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        Boolean result = false;
        //删除选项
        List<ProjectReviewOptions> optionsList = projectReviewOptionsMapper.selectList(new QueryWrapper<ProjectReviewOptions>().eq("project_review_id", id));
        if (optionsList.size() > 0) {
            ProjectReviewOptions options = new ProjectReviewOptions();
            options.setIsDeleted(1);
            result = projectReviewOptionsMapper.update(options,new QueryWrapper<ProjectReviewOptions>().eq("project_review_id",id)) > 0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        List<ProjectReviewDetailed> detailedList = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>().eq("project_review_id", id));
        if (detailedList.size() > 0) {
            //删除维度表
            ProjectReviewDetailed detailed = new ProjectReviewDetailed();
            detailed.setIsDeleted(1);
            result = projectReviewDetailedMapper.update(detailed,new QueryWrapper<ProjectReviewDetailed>().eq("project_review_id",id))>0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        ElsProjectReview projectReview = new ElsProjectReview();
        projectReview.setIsDeleted(1);
        projectReview.setId(id);
        result = elsProjectReviewMapper.updateById(projectReview) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertAnswerProReview(ProjectReviewVO elsProjectReview) {
        ElsProjectReview basic = elsProjectReview.getBasic();
        basic.setTemplateId(basic.getId());
        basic.setCreatedTime(new Date());
        basic.setUpdatedTime(new Date());
        basic.setCreatedBy(AuthUtil.getUserId());
        basic.setUpdatedBy(AuthUtil.getUserId());
        basic.setId(null);
        basic.setUserId(AuthUtil.getUserId());
        //待审核  向小组绑定专家
        basic.setLeaderAuthResult(0);
        int i = elsProjectReviewMapper.selectNotLeaderAuthCount(basic.getProjectId());
        if (i>0) {
            QueryWrapper<ElsProjectReview> wrapper = new QueryWrapper<>();
            wrapper.eq("project_id",basic.getProjectId()).eq("user_id",basic.getUserId());
            int delete = elsProjectReviewMapper.delete(wrapper);
        }
        Boolean result = elsProjectReviewMapper.insert(basic) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        Long projectId = basic.getProjectId();
        Long projectReviewId = basic.getId();

        //待组长审核 向小组绑定项目
        ElsProjects elsProjects = elsProjectsMapper.selectById(basic.getProjectId());
        elsProjects.setStatus(1);
        result = elsProjectsMapper.updateById(elsProjects) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        //获取一级维度  专家和项目进行绑定
        List<ProjectReviewDetailedVO> oneLevelList = setProjectIdAndCreateUser(projectId, projectReviewId, elsProjectReview.getOneLevel());
        result = saveLowerLevel(projectId, projectReviewId, oneLevelList);
        return result;
    }

    private Boolean saveLowerLevel(Long projectId, Long projectReviewId, List<ProjectReviewDetailedVO> levelList) {
        Boolean result = false;
        for (ProjectReviewDetailedVO level : levelList) {
            //判断是否有下级维度
            Integer lowerLevelNum = level.getLowerLevelNum();
            List<String> answerList = new ArrayList<>();
            List<String> optionsList = new ArrayList<>();
            if (lowerLevelNum == 0) {

                List<ProjectReviewOptions> optionList = level.getOptionList();
                String[] answer = null;
                if (StrUtil.isNotEmpty(level.getAnswer())) {
                    answer = level.getAnswer().split(",");
                }
                answerList = new ArrayList<>();
                for (ProjectReviewOptions projectReviewOptions : optionList) {

                    Boolean flag = false;
                    if (ObjectUtil.isNotNull(answer)) {
                        for (String s : answer) {
                            if (projectReviewOptions.getId().toString().equals(s)) {
                                flag = true;
                                break;
                            }
                        }
                    }
                    projectReviewOptions.setCreatedBy(AuthUtil.getUserId());
                    projectReviewOptions.setCreatedTime(new Date());
                    projectReviewOptions.setProjectReviewId(projectReviewId);
                    result = projectReviewOptionsMapper.saveOptions(projectReviewOptions) > 0;
                    optionsList.add(projectReviewOptions.getId().toString());
                    if (flag) {
                        answerList.add(projectReviewOptions.getId().toString());
                    }
                }
            }

            String join = answerList.stream().collect(Collectors.joining(","));
            String options = optionsList.stream().collect(Collectors.joining(","));
            //保存一级维度
            level.setAnswer(join);
            level.setOptionIds(options);
            level.setProjectId(projectId);
            level.setProjectReviewId(projectReviewId);
            level.setCreatedBy(AuthUtil.getUserId());
            level.setCreatedTime(new Date());
            result = projectReviewDetailedMapper.saveReview(level) > 0;
            if (lowerLevelNum > 0) {
                List<ProjectReviewDetailedVO> twoLevelList = level.getLowerLevel();
                for (ProjectReviewDetailedVO projectReviewDetailedVO : twoLevelList) {
                    projectReviewDetailedVO.setParentId(level.getId());
                }
                saveLowerLevel(projectId, projectReviewId, twoLevelList);
            }
        }
        return result;
    }

    private List<ProjectReviewDetailedVO> setProjectIdAndCreateUser(Long projectId, Long projectReviewId, List<ProjectReviewDetailedVO> dataList) {
        for (int i = 0; i < dataList.size(); i++) {
            ProjectReviewDetailedVO data = dataList.get(i);
            data.setCreatedBy(AuthUtil.getUserId());
            data.setCreatedTime(new Date());
            data.setProjectId(projectId);
            data.setProjectReviewId(projectReviewId);
        }
        return dataList;
    }

    private List<ProjectReviewOptions> setProjectReviewIdAndCreateUser(Long projectId, Long projectReviewId, List<ProjectReviewOptions> dataList) {
        for (int i = 0; i < dataList.size(); i++) {
            ProjectReviewOptions data = dataList.get(i);
            data.setCreatedBy(AuthUtil.getUserId());
            data.setCreatedTime(new Date());
            data.setProjectId(projectId);
            data.setProjectReviewId(projectReviewId);
        }
        return dataList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateExpertAudit(ProjectReviewAudit expertAudit) {
        ElsProjectReview elsProjectReview = new ElsProjectReview();
        elsProjectReview.setId(expertAudit.getProjectReviewId());
        elsProjectReview.setLeaderAuthResult(expertAudit.getAuthResult());
        elsProjectReview.setLeaderAuthResultRemark(expertAudit.getAuthResultRemark());
        elsProjectReview.setStatus(1);
        elsProjectReview.setLeaderAuthResultLastTime(DateUtil.date());
        boolean result = elsProjectReviewMapper.updateById(elsProjectReview) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        ElsProjectReview pr = elsProjectReviewMapper.selectById(expertAudit.getProjectReviewId());

        Long projectId = pr.getProjectId();

        //检查小组里的所有评分是否已经都通过了，如果都通过了则跳转到管理员审核的步骤
        int count = elsProjectReviewMapper.selectNotLeaderAuthCount(projectId);

        if (count == 0) {
            //跳转到管理员审核
            ElsProjects elsProjects = elsProjectsMapper.selectById(projectId);
            elsProjects.setStatus(2);
            result = elsProjectsMapper.updateById(elsProjects) > 0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //评分表的状态跳转到管理员进行审核
            result = elsProjectReviewMapper.updateToAdminAuthStatus(projectId) > 0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }

        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateAdminAudit(ProjectReviewAudit expertAudit) {
        ElsProjectReview elsProjectReview = new ElsProjectReview();
        elsProjectReview.setId(expertAudit.getProjectReviewId());
        elsProjectReview.setAdminAuthResult(expertAudit.getAuthResult());
        elsProjectReview.setAdminAuthResultRemark(expertAudit.getAuthResultRemark());
        elsProjectReview.setStatus(2);
        elsProjectReview.setAdminAuthResultLastTime(DateUtil.date());
        boolean result = elsProjectReviewMapper.updateById(elsProjectReview) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        ElsProjectReview pr = elsProjectReviewMapper.selectById(expertAudit.getProjectReviewId());

        Long projectId = pr.getProjectId();

        //检查小组里的所有评分是否已经都通过了，如果都通过了则跳转到管理员审核的步骤
        int count = elsProjectReviewMapper.selectNotAdminAuthCount(projectId);

        if (count == 0) {
            //审核完成
            ElsProjects elsProjects = elsProjectsMapper.selectById(projectId);
            elsProjects.setStatus(99);
            result = elsProjectsMapper.updateById(elsProjects) > 0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //评分表的状态跳转到已完成
            result = elsProjectReviewMapper.updateToCompletedStatus(projectId) > 0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }

        return result;
    }

    @Override
    public List<ProjectReviewZGPXExcel> exportZGPX(Long baseRole,String projectName, Long teamId,Integer status) {
        List<ElsProjectTeamAuditVO> projectsList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Page<ElsProjectTeamAuditVO> elsProjectsPage = new Page<>(-1, -1);
        if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_EXPERT_ROLE)) {
            Page<ElsProjectTeamAuditVO> page = elsProjectsMapper.paginQueryTeamAudit(elsProjectsPage, projectName, year, 1, AuthUtil.getUserId(),teamId,status);
            projectsList = page.getRecords();
        } else {
            Page<ElsProjectTeamAuditVO> page  = elsProjectsMapper.paginQueryAdminAudit(elsProjectsPage,projectName,year,1,teamId,status);
            projectsList = page.getRecords();
        }

        List<ProjectReviewZGPXExcel> result = new ArrayList<>();
        for (ElsProjects projects : projectsList) {
            List<ElsProjectReview> projectReviewList = elsProjectReviewMapper
                    .selectList(new QueryWrapper<ElsProjectReview>().eq("project_id", projects.getId()));

            List<ProjectReviewZGPXExcel> list = new ArrayList<>();
            for (ElsProjectReview elsProjectReview : projectReviewList) {
                User user = userMapper.selectByIdForAll(elsProjectReview.getUserId());
                ProjectReviewZGPXExcel excel = new ProjectReviewZGPXExcel();
                Long projectReviewId = elsProjectReview.getId();
                List<ProjectReviewDetailed> detailedList = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("can_options", 1).eq("project_review_id", projectReviewId).eq("is_reject_option",1));
                if (detailedList.size() > 0) {
                    excel.setUserName(user.getUserName());
                    excel.setTotal("0.0");
                    excel.setRemark(user.getUserName() + "选择了否决项" + "\r\n");
                    if (StrUtil.isEmpty(elsProjectReview.getRejectDes())) {
                        excel.setRejectDes("");
                    } else {
                        excel.setRejectDes(elsProjectReview.getRejectDes());
                    }
                    excel.setIsRejectOption(1);
                    list.add(excel);
                    continue;
                }
                excel.setIsRejectOption(0);
                //二级维度
                Integer level = projectReviewDetailedMapper.selectMaxLevel(projectReviewId);
                //二级维度
                List<ProjectReviewDetailed> projectReviewDetaileds = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("level", 2).eq("project_review_id", projectReviewId));
                for (ProjectReviewDetailed two : projectReviewDetaileds) {
                    //获取三级维度下面有选项的
                    List<ProjectReviewDetailed> three = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>().eq("parent_id", two.getId()).ne("answer", ""));
                    ProjectReviewOptions options = null;
                    Double optionScore = 0.0;
                    if (three.size() > 0) {
                        for (ProjectReviewDetailed projectReviewDetailed : three) {
                            if (ObjectUtil.isNotNull(projectReviewDetailed)) {
                                //查询该选项的分值
                                options = projectReviewOptionsMapper.selectOne(new QueryWrapper<ProjectReviewOptions>().eq("id", projectReviewDetailed.getAnswer()));
                                optionScore += options.getOptionScore();
                            }
                        }
                    }
                    double score = 0.0;
                    if (ObjectUtil.isNull(options)) {
                        score = two.getScore();
                    } else {
                        score =  two.getScore() - optionScore;
                    }
                    switch (two.getName()) {
                        case "依据充分" :
                            excel.setYjcf(String.valueOf(score));
                            break;
                        case "目的明确" :
                            excel.setMdmq(String.valueOf(score));
                            break;
                        case "方案合理" :
                            excel.setFahl(String.valueOf(score));
                            break;
                        case "计划周全" :
                            excel.setJhzq(String.valueOf(score));
                            break;
                        case "总量合理" :
                            excel.setZlhl(String.valueOf(score));
                            break;
                        case "单项合规" :
                            excel.setDxhg(String.valueOf(score));
                            break;
                        case "储备表规范" :
                            excel.setXmcbbgf(String.valueOf(score));
                            break;
                        case "项目层级规范" :
                            excel.setXmcjgf(String.valueOf(score));
                            break;
                        case "可研规范" :
                            excel.setXmkybggf(String.valueOf(score));
                            break;
                    }
                }
                excel.setTotal(String.valueOf(elsProjectReview.getFinalScore()));
                excel.setUserName(user.getUserName());
                excel.setRemark(elsProjectReview.getRemark());
                list.add(excel);
            }
            ProjectReviewZGPXExcel excel = new ProjectReviewZGPXExcel();
            //依据充分
            List<String> yjcfList = list.stream().map(ProjectReviewZGPXExcel::getYjcf).collect(Collectors.toList());
            String yjcf = calculateAverage(yjcfList, projectReviewList.size());
            excel.setYjcf(yjcf);
            //目的明确
            List<String> mdmqList = list.stream().map(ProjectReviewZGPXExcel::getMdmq).collect(Collectors.toList());
            String mdmq = calculateAverage(mdmqList, projectReviewList.size());
            excel.setMdmq(mdmq);
            //方案合理
            List<String> fahlList = list.stream().map(ProjectReviewZGPXExcel::getFahl).collect(Collectors.toList());
            String fahl = calculateAverage(fahlList, projectReviewList.size());
            excel.setFahl(fahl);
            //计划周全
            List<String> jhzqList = list.stream().map(ProjectReviewZGPXExcel::getJhzq).collect(Collectors.toList());
            String jhzq = calculateAverage(jhzqList, projectReviewList.size());
            excel.setJhzq(jhzq);
            //总量合理
            List<String> zlhlList = list.stream().map(ProjectReviewZGPXExcel::getZlhl).collect(Collectors.toList());
            String zlhl = calculateAverage(zlhlList, projectReviewList.size());
            excel.setZlhl(zlhl);
            //单项合规
            List<String> dxhgList = list.stream().map(ProjectReviewZGPXExcel::getDxhg).collect(Collectors.toList());
            String dxhg = calculateAverage(dxhgList, projectReviewList.size());
            excel.setDxhg(dxhg);
            //储备表规范
            List<String> cbbgfList = list.stream().map(ProjectReviewZGPXExcel::getXmcbbgf).collect(Collectors.toList());
            String cbbgf = calculateAverage(cbbgfList, projectReviewList.size());
            excel.setXmcbbgf(cbbgf);
            //项目层级规范
            List<String> xmcjList = list.stream().map(ProjectReviewZGPXExcel::getXmcjgf).collect(Collectors.toList());
            String xmcj = calculateAverage(xmcjList, projectReviewList.size());
            excel.setXmcjgf(xmcj);
            //可研规范
            List<String> kybgList = list.stream().map(ProjectReviewZGPXExcel::getXmkybggf).collect(Collectors.toList());
            String kybg = calculateAverage(kybgList, projectReviewList.size());
            excel.setXmkybggf(kybg);
            //可研规范
            List<String> totalList = list.stream().map(ProjectReviewZGPXExcel::getTotal).collect(Collectors.toList());
            String total = calculateAverage(totalList, projectReviewList.size());
            excel.setTotal(total);
            StringBuilder sbUser = new StringBuilder();
            StringBuilder sbBz = new StringBuilder();

            for (int i = 0; i < list.size(); i++) {
                Integer a = i+ 1;
                if (list.get(i).getIsRejectOption() == 1) {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "    评审原因：" + list.get(i).getRejectDes() + "\r\n");
                } else {
                    sbUser.append(a + "：" +list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "\r\n");
                }
                sbBz.append(list.get(i).getRemark());
            }
            excel.setUserName(sbUser.toString());
            excel.setRemark(sbBz.toString());
            excel.setOrgName(projects.getOrgName());
            excel.setProjectName(projects.getProjectName());
            excel.setProjectOrgName(projects.getProjectOrgName());
            excel.setOrg(projects.getProjectOrgName());
            result.add(excel);
        }

        return result;
    }

    @Override
    public List<ProjectReviewRCPJExcel> exportRCPJ(Long baseRole ,String projectName, Long teamId,Integer status) {
        List<ElsProjectTeamAuditVO> projectsList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Page<ElsProjectTeamAuditVO> elsProjectsPage = new Page<>(-1, -1);
        if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_EXPERT_ROLE)) {
            Page<ElsProjectTeamAuditVO> page = elsProjectsMapper.paginQueryTeamAudit(elsProjectsPage, projectName, year, 2, AuthUtil.getUserId(),teamId,status);
            projectsList = page.getRecords();
        } else {
            Page<ElsProjectTeamAuditVO> page  = elsProjectsMapper.paginQueryAdminAudit(elsProjectsPage,projectName,year,2,teamId,status);
            projectsList = page.getRecords();
        }
        List<ProjectReviewRCPJExcel> result = new ArrayList<>();
        for (ElsProjects projects : projectsList) {
            List<ElsProjectReview> projectReviewList = elsProjectReviewMapper
                    .selectList(new QueryWrapper<ElsProjectReview>().eq("project_id", projects.getId()));

            List<ProjectReviewRCPJExcel> list = new ArrayList<>();
            for (ElsProjectReview elsProjectReview : projectReviewList) {
                User user = userMapper.selectByIdForAll(elsProjectReview.getUserId());
                ProjectReviewRCPJExcel excel = new ProjectReviewRCPJExcel();
                Long projectReviewId = elsProjectReview.getId();
                List<ProjectReviewDetailed> detailedList = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("can_options", 1).eq("project_review_id", projectReviewId).eq("is_reject_option",1));
                if (detailedList.size() > 0) {
                    excel.setUserName(user.getUserName());
                    excel.setTotal("0.0");
                    excel.setRemark(user.getUserName() + "选择了否决项" + "\r\n");
                    if (StrUtil.isEmpty(elsProjectReview.getRejectDes())) {
                        excel.setRejectDes("");
                    } else {
                        excel.setRejectDes(elsProjectReview.getRejectDes());
                    }
                    excel.setIsRejectOption(1);
                    list.add(excel);
                    continue;
                }
                excel.setIsRejectOption(0);
                //二级维度
                Integer level = projectReviewDetailedMapper.selectMaxLevel(projectReviewId);
                //二级维度
                List<ProjectReviewDetailed> projectReviewDetaileds = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("level", 2).eq("project_review_id", projectReviewId));
                for (ProjectReviewDetailed two : projectReviewDetaileds) {
                    //获取三级维度下面有选项的
                    List<ProjectReviewDetailed> three = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>().eq("parent_id", two.getId()).ne("answer", ""));
                    ProjectReviewOptions options = null;
                    Double optionsScore = 0.0;
                    for (ProjectReviewDetailed projectReviewDetailed : three) {
                        if (ObjectUtil.isNotNull(projectReviewDetailed)) {
                            //查询该选项的分值
                            options = projectReviewOptionsMapper.selectOne(new QueryWrapper<ProjectReviewOptions>().eq("id", projectReviewDetailed.getAnswer()));
                            optionsScore += options.getOptionScore();
                        }
                    }

                    double score = 0.0;
                    if (ObjectUtil.isNull(options)) {
                        score = two.getScore();
                    } else {
                        score =  two.getScore() - optionsScore;
                    }
                    //计算该二级维度得分
                    switch (two.getName()) {
                        case "依据充分":
                            excel.setYjcf(String.valueOf(score));
                            break;
                        case "目的明确":
                            excel.setMdmq(String.valueOf(score));
                            break;
                        case "方案合理":
                            excel.setFahl(String.valueOf(score));
                            break;
                        case "计划周全":
                            excel.setJhzq(String.valueOf(score));
                            break;
                        case "总量合理":
                            excel.setZlhl(String.valueOf(score));
                            break;
                        case "单项合规":
                            excel.setDxhg(String.valueOf(score));
                            break;
                        case "储备表规范":
                            excel.setXmcbbgf(String.valueOf(score));
                            break;
                        case "可研规范":
                            excel.setXmkybggf(String.valueOf(score));
                            break;
                    }
                }
                excel.setTotal(String.valueOf(elsProjectReview.getFinalScore()));
                excel.setUserName(user.getUserName());
                excel.setRemark(elsProjectReview.getRemark());
                list.add(excel);
            }
            ProjectReviewRCPJExcel excel = new ProjectReviewRCPJExcel();
            //依据充分
            List<String> yjcfList = list.stream().map(ProjectReviewRCPJExcel::getYjcf).collect(Collectors.toList());
            String yjcf = calculateAverage(yjcfList, projectReviewList.size());
            excel.setYjcf(yjcf);
            //目的明确
            List<String> mdmqList = list.stream().map(ProjectReviewRCPJExcel::getMdmq).collect(Collectors.toList());
            String mdmq = calculateAverage(mdmqList, projectReviewList.size());
            excel.setMdmq(mdmq);
            //方案合理
            List<String> fahlList = list.stream().map(ProjectReviewRCPJExcel::getFahl).collect(Collectors.toList());
            String fahl = calculateAverage(fahlList, projectReviewList.size());
            excel.setFahl(fahl);
            //计划周全
            List<String> jhzqList = list.stream().map(ProjectReviewRCPJExcel::getJhzq).collect(Collectors.toList());
            String jhzq = calculateAverage(jhzqList, projectReviewList.size());
            excel.setJhzq(jhzq);
            //总量合理
            List<String> zlhlList = list.stream().map(ProjectReviewRCPJExcel::getZlhl).collect(Collectors.toList());
            String zlhl = calculateAverage(zlhlList, projectReviewList.size());
            excel.setZlhl(zlhl);
            //单项合规
            List<String> dxhgList = list.stream().map(ProjectReviewRCPJExcel::getDxhg).collect(Collectors.toList());
            String dxhg = calculateAverage(dxhgList, projectReviewList.size());
            excel.setDxhg(dxhg);
            //储备表规范
            List<String> cbbgfList = list.stream().map(ProjectReviewRCPJExcel::getXmcbbgf).collect(Collectors.toList());
            String cbbgf = calculateAverage(cbbgfList, projectReviewList.size());
            excel.setXmcbbgf(cbbgf);
            //可研规范
            List<String> kybgList = list.stream().map(ProjectReviewRCPJExcel::getXmkybggf).collect(Collectors.toList());
            String kybg = calculateAverage(kybgList, projectReviewList.size());
            excel.setXmkybggf(kybg);
            //可研规范
            List<String> totalList = list.stream().map(ProjectReviewRCPJExcel::getTotal).collect(Collectors.toList());
            String total = calculateAverage(totalList, projectReviewList.size());
            excel.setTotal(total);
            StringBuilder sbUser = new StringBuilder();
            StringBuilder sbBz = new StringBuilder();

            for (int i = 0; i < list.size(); i++) {
                Integer a = i + 1;
                if (list.get(i).getIsRejectOption() == 1) {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "    评审原因：" + list.get(i).getRejectDes() + "\r\n");
                } else {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "\r\n");
                }
                sbBz.append(list.get(i).getRemark());
            }
            excel.setUserName(sbUser.toString());
            excel.setRemark(sbBz.toString());
            excel.setProjectName(projects.getProjectName());
            excel.setOrgName(projects.getOrgName());
            excel.setProjectOrgName(projects.getProjectOrgName());
            excel.setOrg(projects.getProjectOrgName());
            excel.setProjectNumber(projects.getProjectNumber());
            result.add(excel);
        }
        return result;
    }

    @Override
    public List<ProjectReviewPXKFExcel> exportPXKF(Long baseRole,String projectName, Long teamId,Integer status) {
        List<ElsProjectTeamAuditVO> projectsList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Page<ElsProjectTeamAuditVO> elsProjectsPage = new Page<>(-1, -1);
        if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_EXPERT_ROLE)) {
            Page<ElsProjectTeamAuditVO> page = elsProjectsMapper.paginQueryTeamAudit(elsProjectsPage, projectName, year, 4, AuthUtil.getUserId(),teamId,status);
            projectsList = page.getRecords();
        } else {
            Page<ElsProjectTeamAuditVO> page  = elsProjectsMapper.paginQueryAdminAudit(elsProjectsPage,projectName,year,4,teamId,status);
            projectsList = page.getRecords();
        }
        List<ProjectReviewPXKFExcel> result = new ArrayList<>();
        for (ElsProjects projects : projectsList) {
            List<ElsProjectReview> projectReviewList = elsProjectReviewMapper
                    .selectList(new QueryWrapper<ElsProjectReview>().eq("project_id", projects.getId()));

            List<ProjectReviewPXKFExcel> list = new ArrayList<>();
            for (ElsProjectReview elsProjectReview : projectReviewList) {
                User user = userMapper.selectByIdForAll(elsProjectReview.getUserId());
                ProjectReviewPXKFExcel excel = new ProjectReviewPXKFExcel();
                Long projectReviewId = elsProjectReview.getId();
                List<ProjectReviewDetailed> detailedList = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("can_options", 1).eq("project_review_id", projectReviewId).eq("is_reject_option",1));
                if (detailedList.size() > 0) {
                    excel.setUserName(user.getUserName());
                    excel.setTotal("0.0");
                    excel.setRemark(user.getUserName() + "选择了否决项" + "\r\n");
                    if (StrUtil.isEmpty(elsProjectReview.getRejectDes())) {
                        excel.setRejectDes("");
                    } else {
                        excel.setRejectDes(elsProjectReview.getRejectDes());
                    }
                    excel.setIsRejectOption(1);
                    list.add(excel);
                    continue;
                }
                excel.setIsRejectOption(0);
                //二级维度
                List<ProjectReviewDetailed> projectReviewDetaileds = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("can_options", 1).eq("project_review_id", projectReviewId));
                for (ProjectReviewDetailed two : projectReviewDetaileds) {
                    //获取三级维度下面有选项的
                     ProjectReviewOptions options = null;
                    if (ObjectUtil.isNotNull(two)) {
                        //查询该选项的分值
                        options = projectReviewOptionsMapper.selectOne(new QueryWrapper<ProjectReviewOptions>().eq("id", two.getAnswer()));
                    }
                    double score = 0.0;
                    if (ObjectUtil.isNotNull(options)) {
                        score =  options.getOptionScore();
                    }
                    //计算该二级维度得分
                    switch (two.getName()) {
                        case "开发背景":
                            excel.setKfbj(String.valueOf(score));
                            break;
                        case "现状描述":
                            excel.setZxms(String.valueOf(score));
                            break;
                        case "立项依据":
                            excel.setLxyj(String.valueOf(score));
                            break;
                        case "开发目标":
                            excel.setKfmb(String.valueOf(score));
                            break;
                        case "开发内容":
                            excel.setKfnr(String.valueOf(score));
                            break;
                        case "开发流程":
                            excel.setKflc(String.valueOf(score));
                            break;
                        case "预算合理":
                            excel.setYshl(String.valueOf(score));
                            break;
                        case "创新性":
                            excel.setCxx(String.valueOf(score));
                            break;
                        case "实用性":
                            excel.setSyx(String.valueOf(score));
                            break;
                        case "规范性完整性":
                            excel.setGfxWzx(String.valueOf(score));
                            break;
                    }
                }
                excel.setTotal(String.valueOf(elsProjectReview.getFinalScore()));
                excel.setUserName(user.getUserName());
                excel.setRemark(elsProjectReview.getRemark());
                list.add(excel);
            }
            ProjectReviewPXKFExcel excel = new ProjectReviewPXKFExcel();
            //开发背景
            List<String> yjcfList = list.stream().map(ProjectReviewPXKFExcel::getKfbj).collect(Collectors.toList());
            String yjcf = calculateAverage(yjcfList, projectReviewList.size());
            excel.setKfbj(yjcf);
            //目的明确
            List<String> mdmqList = list.stream().map(ProjectReviewPXKFExcel::getZxms).collect(Collectors.toList());
            String mdmq = calculateAverage(mdmqList, projectReviewList.size());
            excel.setZxms(mdmq);
            //方案合理
            List<String> fahlList = list.stream().map(ProjectReviewPXKFExcel::getLxyj).collect(Collectors.toList());
            String fahl = calculateAverage(fahlList, projectReviewList.size());
            excel.setLxyj(fahl);
            //计划周全
            List<String> jhzqList = list.stream().map(ProjectReviewPXKFExcel::getKfmb).collect(Collectors.toList());
            String jhzq = calculateAverage(jhzqList, projectReviewList.size());
            excel.setKfmb(jhzq);
            //总量合理
            List<String> zlhlList = list.stream().map(ProjectReviewPXKFExcel::getKfnr).collect(Collectors.toList());
            String zlhl = calculateAverage(zlhlList, projectReviewList.size());
            excel.setKfnr(zlhl);
            //单项合规
            List<String> dxhgList = list.stream().map(ProjectReviewPXKFExcel::getKflc).collect(Collectors.toList());
            String dxhg = calculateAverage(dxhgList, projectReviewList.size());
            excel.setKflc(dxhg);
            //储备表规范
            List<String> cbbgfList = list.stream().map(ProjectReviewPXKFExcel::getYshl).collect(Collectors.toList());
            String cbbgf = calculateAverage(cbbgfList, projectReviewList.size());
            excel.setYshl(cbbgf);
            //可研规范
            List<String> kybgList = list.stream().map(ProjectReviewPXKFExcel::getCxx).collect(Collectors.toList());
            String kybg = calculateAverage(kybgList, projectReviewList.size());
            excel.setCxx(kybg);
            //实用性
            List<String> syxList = list.stream().map(ProjectReviewPXKFExcel::getSyx).collect(Collectors.toList());
            String syx = calculateAverage(syxList, projectReviewList.size());
            excel.setSyx(syx);
            //实用性
            List<String> gfxwzxList = list.stream().map(ProjectReviewPXKFExcel::getGfxWzx).collect(Collectors.toList());
            String gfxwzx = calculateAverage(gfxwzxList, projectReviewList.size());
            excel.setGfxWzx(gfxwzx);
            List<String> totalList = list.stream().map(ProjectReviewPXKFExcel::getTotal).collect(Collectors.toList());
            String total = calculateAverage(totalList, projectReviewList.size());
            excel.setTotal(total);
            StringBuilder sbUser = new StringBuilder();
            StringBuilder sbBz = new StringBuilder();

            for (int i = 0; i < list.size(); i++) {
                Integer a = i + 1;
                if (list.get(i).getIsRejectOption() == 1) {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "    评审原因：" + list.get(i).getRejectDes() + "\r\n");
                } else {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "\r\n");
                }
                sbBz.append(list.get(i).getRemark());
            }
            excel.setUserName(sbUser.toString());
            excel.setRemark(sbBz.toString());
            excel.setProjectName(projects.getProjectName());
            excel.setOrgName(projects.getOrgName());
            excel.setProjectOrgName(projects.getProjectOrgName());
            excel.setOrg(projects.getProjectOrgName());
            excel.setProjectNumber(projects.getProjectNumber());
            result.add(excel);
        }
        return result;
    }

    @Override
    public List<ProjectReviewPXKFExcel> exportPXGZ(Long baseRole,String projectName, Long teamId,Integer status ) {
        List<ElsProjectTeamAuditVO> projectsList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Page<ElsProjectTeamAuditVO> elsProjectsPage = new Page<>(-1, -1);
        if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_EXPERT_ROLE)) {
            Page<ElsProjectTeamAuditVO> page = elsProjectsMapper.paginQueryTeamAudit(elsProjectsPage, projectName, year, 8, AuthUtil.getUserId(),teamId,status);
            projectsList = page.getRecords();
        } else {
            Page<ElsProjectTeamAuditVO> page  = elsProjectsMapper.paginQueryAdminAudit(elsProjectsPage,projectName,year,8,teamId,status);
            projectsList = page.getRecords();
        }
        List<ProjectReviewPXKFExcel> result = new ArrayList<>();
        for (ElsProjects projects : projectsList) {
            List<ElsProjectReview> projectReviewList = elsProjectReviewMapper
                    .selectList(new QueryWrapper<ElsProjectReview>().eq("project_id", projects.getId()));

            List<ProjectReviewPXKFExcel> list = new ArrayList<>();
            for (ElsProjectReview elsProjectReview : projectReviewList) {
                User user = userMapper.selectByIdForAll(elsProjectReview.getUserId());
                ProjectReviewPXKFExcel excel = new ProjectReviewPXKFExcel();
                Long projectReviewId = elsProjectReview.getId();
                List<ProjectReviewDetailed> detailedList = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("can_options", 1).eq("project_review_id", projectReviewId).eq("is_reject_option",1));
                if (detailedList.size() > 0) {
                    excel.setUserName(user.getUserName());
                    excel.setTotal("0.0");
                    excel.setRemark(user.getUserName() + "选择了否决项" + "\r\n");
                    if (StrUtil.isEmpty(elsProjectReview.getRejectDes())) {
                        excel.setRejectDes("");
                    } else {
                        excel.setRejectDes(elsProjectReview.getRejectDes());
                    }
                    excel.setIsRejectOption(1);
                    list.add(excel);
                    continue;
                }
                excel.setIsRejectOption(0);
                //二级维度
                Integer level = projectReviewDetailedMapper.selectMaxLevel(projectReviewId);
                //二级维度
                List<ProjectReviewDetailed> projectReviewDetaileds = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("level", 3).eq("project_review_id", projectReviewId));
                for (ProjectReviewDetailed two : projectReviewDetaileds) {
                    //获取三级维度下面有选项的
                    ProjectReviewOptions options = null;
                    if (ObjectUtil.isNotNull(two)) {
                        //查询该选项的分值
                        options = projectReviewOptionsMapper.selectOne(new QueryWrapper<ProjectReviewOptions>().eq("id", two.getAnswer()));
                    }
                    double score = 0.0;
                    if (ObjectUtil.isNotNull(options)) {
                        score =  options.getOptionScore();
                    }
                    //计算该二级维度得分
                    switch (two.getName()) {
                        case "开发背景":
                            excel.setKfbj(String.valueOf(score));
                            break;
                        case "现状描述":
                            excel.setZxms(String.valueOf(score));
                            break;
                        case "立项依据":
                            excel.setLxyj(String.valueOf(score));
                            break;
                        case "开发目标":
                            excel.setKfmb(String.valueOf(score));
                            break;
                        case "开发内容":
                            excel.setKfnr(String.valueOf(score));
                            break;
                        case "开发流程":
                            excel.setKflc(String.valueOf(score));
                            break;
                        case "预算合理":
                            excel.setYshl(String.valueOf(score));
                            break;
                        case "创新性":
                            excel.setCxx(String.valueOf(score));
                            break;
                        case "实用性":
                            excel.setSyx(String.valueOf(score));
                            break;
                        case "规范性完整性":
                            excel.setGfxWzx(String.valueOf(score));
                            break;
                    }
                }
                excel.setTotal(String.valueOf(elsProjectReview.getFinalScore()));
                excel.setUserName(user.getUserName());
                excel.setRemark(elsProjectReview.getRemark());
                list.add(excel);
            }
            ProjectReviewPXKFExcel excel = new ProjectReviewPXKFExcel();
            //开发背景
            List<String> yjcfList = list.stream().map(ProjectReviewPXKFExcel::getKfbj).collect(Collectors.toList());
            String yjcf = calculateAverage(yjcfList, projectReviewList.size());
            excel.setKfbj(yjcf);
            //目的明确
            List<String> mdmqList = list.stream().map(ProjectReviewPXKFExcel::getZxms).collect(Collectors.toList());
            String mdmq = calculateAverage(mdmqList, projectReviewList.size());
            excel.setZxms(mdmq);
            //方案合理
            List<String> fahlList = list.stream().map(ProjectReviewPXKFExcel::getLxyj).collect(Collectors.toList());
            String fahl = calculateAverage(fahlList, projectReviewList.size());
            excel.setLxyj(fahl);
            //计划周全
            List<String> jhzqList = list.stream().map(ProjectReviewPXKFExcel::getKfmb).collect(Collectors.toList());
            String jhzq = calculateAverage(jhzqList, projectReviewList.size());
            excel.setKfmb(jhzq);
            //总量合理
            List<String> zlhlList = list.stream().map(ProjectReviewPXKFExcel::getKfnr).collect(Collectors.toList());
            String zlhl = calculateAverage(zlhlList, projectReviewList.size());
            excel.setKfnr(zlhl);
            //单项合规
            List<String> dxhgList = list.stream().map(ProjectReviewPXKFExcel::getKflc).collect(Collectors.toList());
            String dxhg = calculateAverage(dxhgList, projectReviewList.size());
            excel.setKflc(dxhg);
            //储备表规范
            List<String> cbbgfList = list.stream().map(ProjectReviewPXKFExcel::getYshl).collect(Collectors.toList());
            String cbbgf = calculateAverage(cbbgfList, projectReviewList.size());
            excel.setYshl(cbbgf);
            //可研规范
            List<String> kybgList = list.stream().map(ProjectReviewPXKFExcel::getCxx).collect(Collectors.toList());
            String kybg = calculateAverage(kybgList, projectReviewList.size());
            excel.setCxx(kybg);
            //实用性
            List<String> syxList = list.stream().map(ProjectReviewPXKFExcel::getSyx).collect(Collectors.toList());
            String syx = calculateAverage(syxList, projectReviewList.size());
            excel.setSyx(syx);
            //实用性
            List<String> gfxwzxList = list.stream().map(ProjectReviewPXKFExcel::getGfxWzx).collect(Collectors.toList());
            String gfxwzx = calculateAverage(gfxwzxList, projectReviewList.size());
            excel.setGfxWzx(gfxwzx);
            List<String> totalList = list.stream().map(ProjectReviewPXKFExcel::getTotal).collect(Collectors.toList());
            String total = calculateAverage(totalList, projectReviewList.size());
            excel.setTotal(total);
            StringBuilder sbUser = new StringBuilder();
            StringBuilder sbBz = new StringBuilder();

            for (int i = 0; i < list.size(); i++) {
                Integer a = i + 1;
                if (list.get(i).getIsRejectOption() == 1) {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "    评审原因：" + list.get(i).getRejectDes() + "\r\n");
                } else {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "\r\n");
                }
                sbBz.append(list.get(i).getRemark());
            }
            excel.setUserName(sbUser.toString());
            excel.setRemark(sbBz.toString());
            excel.setProjectName(projects.getProjectName());
            excel.setOrgName(projects.getOrgName());
            excel.setProjectOrgName(projects.getProjectOrgName());
            excel.setOrg(projects.getProjectOrgName());
            excel.setProjectNumber(projects.getProjectNumber());
            result.add(excel);
        }
        return result;
    }

    @Override
    public List<ProjectReviewJGExcel> exportJG(Long baseRole,String projectName, Long teamId,Integer status ) {
        List<ElsProjectTeamAuditVO> projectsList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Page<ElsProjectTeamAuditVO> elsProjectsPage = new Page<>(-1, -1);
        if (BaseRoleUtil.hasRole(baseRole, BaseRoleConstant.BASE_EXPERT_ROLE)) {
            Page<ElsProjectTeamAuditVO> page = elsProjectsMapper.paginQueryTeamAudit(elsProjectsPage, projectName, year, 16, AuthUtil.getUserId(),teamId,status);
            projectsList = page.getRecords();
        } else {
            Page<ElsProjectTeamAuditVO> page  = elsProjectsMapper.paginQueryAdminAudit(elsProjectsPage,projectName,year,16,teamId,status);
            projectsList = page.getRecords();
        }
        List<ProjectReviewJGExcel> result = new ArrayList<>();
        for (ElsProjects projects : projectsList) {
            List<ElsProjectReview> projectReviewList = elsProjectReviewMapper
                    .selectList(new QueryWrapper<ElsProjectReview>().eq("project_id", projects.getId()));

            List<ProjectReviewJGExcel> list = new ArrayList<>();
            for (ElsProjectReview elsProjectReview : projectReviewList) {
                User user = userMapper.selectByIdForAll(elsProjectReview.getUserId());
                ProjectReviewJGExcel excel = new ProjectReviewJGExcel();
                Long projectReviewId = elsProjectReview.getId();
                List<ProjectReviewDetailed> detailedList = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("can_options", 1).eq("project_review_id", projectReviewId).eq("is_reject_option",1));
                if (detailedList.size() > 0) {
                    excel.setUserName(user.getUserName());
                    excel.setTotal("0.0");
                    excel.setRemark(user.getUserName() + "选择了否决项" + "\r\n");
                    if (StrUtil.isEmpty(elsProjectReview.getRejectDes())) {
                        excel.setRejectDes("");
                    } else {
                        excel.setRejectDes(elsProjectReview.getRejectDes());
                    }
                    excel.setIsRejectOption(1);
                    list.add(excel);
                    continue;
                }
                excel.setIsRejectOption(0);
                //二级维度
                Integer level = projectReviewDetailedMapper.selectMaxLevel(projectReviewId);
                //二级维度
                List<ProjectReviewDetailed> projectReviewDetaileds = projectReviewDetailedMapper.selectList(new QueryWrapper<ProjectReviewDetailed>()
                        .eq("level", 1).eq("project_review_id", projectReviewId));
                for (ProjectReviewDetailed two : projectReviewDetaileds) {
                    //获取三级维度下面有选项的
                    ProjectReviewOptions options = null;
                    if (ObjectUtil.isNotNull(two)) {
                        //查询该选项的分值
                        options = projectReviewOptionsMapper.selectOne(new QueryWrapper<ProjectReviewOptions>().eq("id", two.getAnswer()));
                    }
                    double score = 0.0;
                    if (ObjectUtil.isNotNull(options)) {
                        score =  options.getOptionScore();
                    }
                    //计算该二级维度得分
                    switch (two.getName()) {
                        case "（一）报告格式规范性（5分）":
                            excel.setBggsgfx(String.valueOf(score));
                            break;
                        case "（二）项目概况介绍（10分）":
                            excel.setProjectGkjs(String.valueOf(score));
                            break;
                        case "（三）项目必要性（25分）":
                            excel.setProjectByx(String.valueOf(score));
                            break;
                        case "（四）项目可行性（10分）":
                            excel.setProjectKxx(String.valueOf(score));
                            break;
                        case "（五）实施方案（35分）":
                            excel.setSsfa(String.valueOf(score));
                            break;
                        case "（六）工期安排及资金概（预）算（10分）":
                            excel.setGqapZjys(String.valueOf(score));
                            break;
                        case "（七）拆除设备（物资）处置方案（5分）":
                            excel.setSbczfa(String.valueOf(score));
                            break;
                    }
                }
                excel.setTotal(String.valueOf(elsProjectReview.getFinalScore()));
                excel.setUserName(user.getUserName());
                excel.setRemark(elsProjectReview.getRemark());
                list.add(excel);
            }
            ProjectReviewJGExcel excel = new ProjectReviewJGExcel();
            //开发背景
            List<String> yjcfList = list.stream().map(ProjectReviewJGExcel::getBggsgfx).collect(Collectors.toList());
            String yjcf = calculateAverage(yjcfList, projectReviewList.size());
            excel.setBggsgfx(yjcf);
            //目的明确
            List<String> mdmqList = list.stream().map(ProjectReviewJGExcel::getProjectGkjs).collect(Collectors.toList());
            String mdmq = calculateAverage(mdmqList, projectReviewList.size());
            excel.setProjectGkjs(mdmq);
            //方案合理
            List<String> fahlList = list.stream().map(ProjectReviewJGExcel::getProjectByx).collect(Collectors.toList());
            String fahl = calculateAverage(fahlList, projectReviewList.size());
            excel.setProjectByx(fahl);
            //计划周全
            List<String> jhzqList = list.stream().map(ProjectReviewJGExcel::getProjectKxx).collect(Collectors.toList());
            String jhzq = calculateAverage(jhzqList, projectReviewList.size());
            excel.setProjectKxx(jhzq);
            //总量合理
            List<String> zlhlList = list.stream().map(ProjectReviewJGExcel::getSsfa).collect(Collectors.toList());
            String zlhl = calculateAverage(zlhlList, projectReviewList.size());
            excel.setSsfa(zlhl);
            //单项合规
            List<String> dxhgList = list.stream().map(ProjectReviewJGExcel::getGqapZjys).collect(Collectors.toList());
            String dxhg = calculateAverage(dxhgList, projectReviewList.size());
            excel.setGqapZjys(dxhg);
            //拆除
            List<String> sbwzList = list.stream().map(ProjectReviewJGExcel::getSbczfa).collect(Collectors.toList());
            String sbwz = calculateAverage(sbwzList, projectReviewList.size());
            excel.setSbczfa(sbwz);
            List<String> totalList = list.stream().map(ProjectReviewJGExcel::getTotal).collect(Collectors.toList());
            String total = calculateAverage(totalList, projectReviewList.size());
            excel.setTotal(total);
            StringBuilder sbUser = new StringBuilder();
            StringBuilder sbBz = new StringBuilder();

            for (int i = 0; i < list.size(); i++) {
                Integer a = i + 1;
                if (list.get(i).getIsRejectOption() == 1) {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "    评审原因：" + list.get(i).getRejectDes() + "\r\n");
                } else {
                    sbUser.append(a + "：" + list.get(i).getUserName() + "    " + list.get(i).getTotal() + "分" + "\r\n");
                }
                sbBz.append(list.get(i).getRemark());
            }
            excel.setUserName(sbUser.toString());
            excel.setRemark(sbBz.toString());
            excel.setProjectName(projects.getProjectName());
            excel.setOrgName(projects.getOrgName());
            excel.setProjectOrgName(projects.getProjectOrgName());
            excel.setOrg(projects.getProjectOrgName());
            excel.setProjectNumber(projects.getProjectNumber());
            result.add(excel);
        }
        return result;
    }

    @Override
    public Integer selectByid(Long aLong) {
        return elsProjectReviewMapper.selectByIds(aLong);
    }

    private String calculateAverage(List<String> list, Integer num) {
        Double sum = 0.0;
        for (String s : list) {
            if (ObjectUtil.isNull(s)) {
                continue;
            }
          sum += Double.valueOf(s);
        }
        Double result =  sum / num ;
        if (Double.isNaN(result)) {
            result = 0.0;
        }
        BigDecimal b = new BigDecimal(result);
        double v = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(v);
    }
}
